package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.entity.*;
import com.leyou.item.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.leyou.common.constants.MQConstants.Exchange.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_UP_KEY;

@Service
public class GoodsService {
    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 分页查询spu
     * @param key
     * @param saleable
     * @param page
     * @param rows
     * @return
     */
    public PageResult<SpuDTO> querySpuByPage(String key, Boolean saleable, Integer page, Integer rows) {
        //1.分页
        PageHelper.startPage(page,rows);

        //2.过滤
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //2.1搜索条件过滤
        if (StringUtils.isNoneBlank((key))){
            criteria.andLike("name","%" + key +"%");
        }
        //2.2上下架过滤
        if (saleable != null){
            criteria.andEqualTo("saleable",saleable);
        }
        //2.3默认按时间排序
        example.setOrderByClause("update_time DESC");
        //3.查询结果
        List<Spu> spus = spuMapper.selectByExample(example);

        //4.封装分页结果
        PageInfo<Spu> info = new PageInfo<>(spus);
        //DTO转换
        List<SpuDTO> spuDTOs = BeanHelper.copyWithCollection(spus, SpuDTO.class);

        //处理分类名称和品牌名称
        handleCategoryAndBrandName(spuDTOs);

        return new PageResult<>(info.getTotal(),spuDTOs);
    }

    private void handleCategoryAndBrandName(List<SpuDTO> spuDTOs){
        for (SpuDTO spuDTO : spuDTOs) {
            //查询分类 3个
            String categoryName = categoryService
                    .queryCategoryByIds(spuDTO.getCategoryIds())//通用Mapper查询分类
                    .stream()//循环取出每个对象
                    .map(CategoryDTO::getName)//CategoryDTO -> CategoryDTO.getName
                    .collect(Collectors.joining("/"));//用/作为分隔符
            spuDTO.setCategoryName(categoryName);
            //查询品牌
            BrandDTO brandDTO = brandService.queryById(spuDTO.getBrandId());
            spuDTO.setBrandName(brandDTO.getName());

        }
    }

    /**
     * 新增商品
     * @param spuDTO 包含Spu、SpuDetail、Sku
     */
    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        //从DTO中取出数据spu信息
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        //保存spu
        spu.setId(null);
        spu.setCreateTime(null);
        spu.setSaleable(null);
        int count = spuMapper.insertSelective(spu);
        if (count != 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //初始化SpuDetail信息
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        spuDetail.setSpuId(spu.getId());
        //保存spu详情
        count = spuDetailMapper.insertSelective(spuDetail);
        if (count != 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //准备sku数据
        List<SkuDTO> skuDTOS = spuDTO.getSkus();
        ArrayList<Sku> skus = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOS) {
            skuDTO.setSpuId(spu.getId());
            skus.add(BeanHelper.copyProperties(skuDTO,Sku.class));
        }
        //保存sku
        count = skuMapper.insertList(skus);
        if (count != skus.size()){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }


    /**
     * 修改商品上下架
     * @param id
     * @param saleable
     */
    @Transactional
    public void updateSpuSaleable(Long id, Boolean saleable) {
        //1.更新spu
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //2.更新sku
        //2.1准备sku更新的数据
        Sku sku = new Sku();
        sku.setEnable(saleable);
        //2.2准备sku更新的匹配条件
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId",id);
        count = skuMapper.updateByExampleSelective(sku,example);

        int size = skuMapper.selectCountByExample(example);
        if (count != size){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //发送mq消息
        String key = saleable ? ITEM_UP_KEY : ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME,key,id);
    }


    /**
     * 根据spuId查询spuDetaile
     * @param id
     * @return
     */
    public SpuDetailDTO querySpuDetailById(Long id) {
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(id);
        if (spuDetail == null){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail,SpuDetailDTO.class);
    }

    /**
     * 根据spuID查询sku
     * @param id
     * @return
     */
    public List<SkuDTO> querySkuBySpuId(Long id) {
        Sku sku = new Sku();
        sku.setSpuId(id);
        List<Sku> skus = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(skus)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skus,SkuDTO.class);
    }

    /**
     * 修改商品
     * @param spuDTO
     */
    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        Long spuId = spuDTO.getId();
        if (spuId == null){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        //1.删除sku
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        //查询数量
        int size = skuMapper.selectCount(sku);
        if (size > 0){
            int count = skuMapper.delete(sku);
            if (count != size){
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }

        //2.更新spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(null);
        spu.setCreateTime(null);
        spu.setUpdateTime(null);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //3.更新spuDetail
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        spuDetail.setSpuId(spuId);
        spuDetail.setCreateTime(null);
        spuDetail.setUpdateTime(null);
        count = spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
        if (count != 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //4.新增sku
        List<SkuDTO> skuDTOs = spuDTO.getSkus();
        //处理DTO
        List<Sku> skus = skuDTOs.stream()
                .map(dto -> {
                    dto.setEnable(false);
                    //添加spu的id
                    dto.setSpuId(spuId);
                    return BeanHelper.copyProperties(dto, Sku.class);
                }).collect(Collectors.toList());

        count = skuMapper.insertList(skus);
        if (count != skus.size()){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }

    /**
     * 通过 id 查询Spu
     * @param id
     * @return
     */
    public SpuDTO querySpuById(Long id) {
        Spu spu = this.spuMapper.selectByPrimaryKey(id);
        if (spu == null){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }

        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);
        spuDTO.setSpuDetail(querySpuDetailById(id));
        spuDTO.setSkus(querySkuBySpuId(id));
        return spuDTO;
    }


    /**
     * 通过 ids 查询List<Sku>
     * @param ids
     * @return
     */
    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        //查询sku
        List<Sku> skuList = skuMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(skuList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skuList,SkuDTO.class);
    }

    /**
     * 扣减库存，基于sku的map集合，map的key存放sku的Id，map的value对应的是当前sku应该扣减的数量
     * @param skuMap
     */
    public void minusStock(Map<Long, Integer> skuMap) {

        //基于sku的id集合查询对应的sku信息
        List<Sku> skus = this.skuMapper.selectByIdList(new ArrayList<>(skuMap.keySet()));

        //循环查询到的sku，把sku对应的库存，做对应的扣减
        for (Sku sku : skus) {
            //sku的数量只能是正数，所以即便减出负值，会直接报错
            sku.setStock(sku.getStock() - skuMap.get(sku.getId()));

            sku.setUpdateTime(new Date());

            this.skuMapper.updateByPrimaryKeySelective(sku);
        }

    }

    /**
     * 加库存，基于sku的map集合，map的key存放sku的Id，map的value对应的是当前sku应该增加的数量
     * @param skuMap
     */
    public void plusStock(Map<Long, Integer> skuMap) {
        //基于sku的id集合查询对应的sku信息
        List<Sku> skus = this.skuMapper.selectByIdList(new ArrayList<>(skuMap.keySet()));

        //循环查询到的sku，把sku对应的库存，做对应的扣减
        for (Sku sku : skus) {
            //sku的数量只能是正数，所以即便减出负值，会直接报错
            sku.setStock(sku.getStock() + skuMap.get(sku.getId()));

            sku.setUpdateTime(new Date());

            this.skuMapper.updateByPrimaryKeySelective(sku);
        }

    }
}
